package com.demo.common;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.demo.itchat.SimpleGpt;
import com.jfinal.kit.PropKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author skip_xie 153993778@qq.com
 */
public class GptApi {

    private static Logger LOG = LoggerFactory.getLogger(GptApi.class);
    // chatGpt Api Key
    private static String token = PropKit.get("gpt_api");
    private static String apiUrl = PropKit.get("api_url");

    private static int timeout = PropKit.getInt("timeout");
    private static int max_tokens = PropKit.getInt("max_tokens");
    private static double temperature = PropKit.getDouble("temperature");

    /**
     * 通过chatApi 获取数据
     * @param text
     * @return
     */
    public String getChatGpt(String text){
        String t = "服务暂时不可以或者出错啦，可以尝试重新发送（可以选择白天进行提问）。";
        try {
            Map<String,String> headers = new HashMap<String,String>();
            headers.put("Content-Type","application/json;charset=UTF-8");

            JSONObject json = new JSONObject();
            //选择模型
            json.set("model","text-davinci-003");
            //添加我们需要输入的内容
            json.set("prompt",text);
            json.set("temperature",temperature);
            json.set("max_tokens",max_tokens);

            HttpResponse response = HttpRequest.post(apiUrl)
                    .headerMap(headers, false)
                    .bearerAuth(token)
                    .body(String.valueOf(json))
                    .timeout(timeout)
                    .execute();

            JSONObject jsonObject2 = JSONUtil.parseObj(response.body());
            JSONArray jsonArray = new JSONArray(jsonObject2.get("choices").toString());
            JSONObject subImageInfoObject = jsonArray.getJSONObject(0);

            t = subImageInfoObject.get("text").toString();
        } catch (Exception e) {
            LOG.error(e.getMessage());
            throw new RuntimeException(e);
        }  finally {
            return t;
        }
    }
}
